package com.leesche.zcsp.node.web.controller.wechat.individual;

import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import com.leesche.zcsp.node.pay.wecha.service.WechatService;
import com.leesche.zcsp.node.pay.wecha.timer.WechatTimer;
import com.leesche.zcsp.node.utils.wechatutils.WechatUtil;
import com.leesche.zcsp.node.web.model.*;
import com.leesche.zcsp.node.web.service.SysNoticeService;
import com.leesche.zcsp.node.web.service.impl.data.read.*;
import com.leesche.zcsp.node.web.vo.ChildUserInfo;
import com.leesche.zcsp.node.web.vo.UserInfo;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.leesche.zcsp.node.utils.web.SessionManager;
import com.leesche.zcsp.node.utils.web.messge.WebResult;
import com.leesche.zcsp.node.web.constants.Constants;
import com.leesche.zcsp.node.web.controller.template.UserTemplate;
import com.leesche.zcsp.node.web.service.SysUserBalanceService;
import com.leesche.zcsp.node.web.service.privilege.PrivilegeService;
import com.leesche.zcsp.node.web.vo.ChildUser;
import com.leesche.zcsp.node.web.vo.UserGroup;

/**
 * @author Jerry Chan
 * @version V1.0
 * @Title: node
 * @Package com.leesche.zcsp.node.web.controller.wechat.individual
 * @Description:( 微信栏目"我的"控制器)
 * @date 2016年10月19日 12:14
 */
@Controller
@RequestMapping("/wechat/indivdual")
public class WechatIndivdualController extends UserTemplate {

    private static final Logger logger = Logger
            .getLogger(WechatIndivdualController.class);

    @Autowired
    private PrivilegeService privilegeService;

    @Autowired
    private SysUserBalanceService sysUserBalanceService;

    @Autowired
    WechatService wechatService;

    @Autowired
    private SysNoticeService sysNoticeService;

    private static final String indexView = "wechat/individual/showView";
    private static final String businessinfoView = "wechat/individual/businessinfo";
    private static final String usergroupView = "wechat/individual/usergroup";
    private static final String childUserView = "wechat/individual/childuser";
    private static final String securityView = "wechat/individual/security";
    private static final String changeMoblieView = "wechat/individual/changemoblie";
    private static final String changeLoginPasswordView = "wechat/individual/changloginpassword";
    private static final String changeTransferPasswordView = "wechat/individual/changtransferpassword";
    private static final String uploadView = "wechat/individual/uploadlogo";
    private static final String appQRCodeView = "wechat/individual/appqrcode";
    private static final String REGISTER_SUSTOMER_VIEW = "wechat/register/customerInfo";

    @RequestMapping(value = "/gotoindex", method = RequestMethod.GET)
    public String showView(Model model) {
        QuerySysUserBalanceCondition querySysUserBalanceCondition = new QuerySysUserBalanceCondition();
        querySysUserBalanceCondition.setUserId(privilegeService
                .getCurrentPrincipal().getUserid());
        model.addAttribute("balances", sysUserBalanceService
                .findByCondition(querySysUserBalanceCondition));
        model.addAttribute("cur", "my");
        return indexView;
    }

    @RequestMapping(value = "/logout", method = RequestMethod.GET)
    public String logout() {

        SessionManager.destroySession();

        return "redirect:/wechat/login/signIn";
    }


    @RequestMapping(value = "/gotoPerfect", method = RequestMethod.GET)
    public String showCustomerInfoView() {
        return REGISTER_SUSTOMER_VIEW;
    }

    /**
     * @Title: showAPPQRCodeView
     * @Description: TODO(展示APP下载二维码)
     * @author Jerry Chen
     * @date 2016年10月22日 下午6:31:27
     */
    @RequestMapping(value = "/appdownloadqrcode", method = RequestMethod.GET)
    public String showAPPQRCodeView() {
        return appQRCodeView;
    }

    /**
     * @Title: uploadUserLogo
     * @Description: TODO(上传Logo, GET请求为:展示上传LOGO界面)
     * @author Jerry Chen
     * @date 2016年10月22日 上午3:05:21
     */
    @RequestMapping(value = "/uploadlogo", method = RequestMethod.GET)
    public String showUploadLogoView(Model model) {
        try {
            String logoUrl = Constants.SYSTEM_DEFAULT_UPLOADIMAGE;
            QuerySysNoticeCondition condition = new QuerySysNoticeCondition();
            condition.setUserid(privilegeService.getCurrentPrincipal().getUserid());
            condition.setQueryAll(true);
            for (SysNoticeDto noticeDto : sysNoticeService.findListsByCondition(condition)) {
                logoUrl = noticeDto.getLogourl();
            }

            model.addAttribute("logourl", logoUrl);

        } catch (Exception e) {
            logger.error(e, e);
        }
        return uploadView;
    }

    /**
     * @param mediaid 媒体ID
     * @Title: uploadUserLogo
     * @Description: TODO(上传Logo, POST请求为:提交数据)
     * @author Jerry Chen
     * @date 2016年10月22日 上午3:05:21
     */
    @ResponseBody
    @RequestMapping(value = "/uploadLogo", method = RequestMethod.POST)
    public Map<String, Object> uploadUserLogo(final @RequestParam String mediaid) {
        String filename = WechatUtil.downloadMedia(WechatTimer.ASSCEE_TOKEN, mediaid, Constants.SYSTEM_TMAGE_USERLOGO_DIRECTORY);
        if (filename != null && !"".equals(filename)) {

            Long usreid = privilegeService.getCurrentPrincipal().getUserid();
            /*SysUser user = new SysUser();
            user.setUserid(usreid);
            user.setAdminid(usreid);
            user.setUpdatetime(new Date());
            user.setUrl(filename);*/

            SysNotice notice = new SysNotice();
            notice.setLogourl(filename);
            notice.setUpdatetime(new Date());
            notice.setAdminid(usreid);
            notice.setUserid(usreid);

            QuerySysNoticeCondition condition = new QuerySysNoticeCondition();
            condition.setUserid(usreid);
            condition.setQueryAll(true);
            List<SysNoticeDto> noticeDtos = sysNoticeService.findListsByCondition(condition);
            if (noticeDtos.size() > 0) {
                SysNoticeCriteria criteria = new SysNoticeCriteria();
                criteria.or().andUseridEqualTo(usreid);
                sysNoticeService.updateByCriteriaSelective(notice, criteria);

            } else {
                sysNoticeService.insertSelective(notice);
            }

           /* sysUserService.updateByPrimaryKeySelective(user);
*/

            return WebResult.success().info("Logo上传成功。").toMap();
        } else {
            return WebResult.failure("上传的Logo失败。").toMap();
        }
    }


    @RequestMapping(value = "/showChangeLoginPassword", method = RequestMethod.GET)
    public String showSeurityChangeLoginPasswordView(Model model) {
        return changeLoginPasswordView;
    }

    @RequestMapping(value = "/showChangeTransferPassword", method = RequestMethod.GET)
    public String showSeurityChangeTransferPasswordView(Model model) {
        return changeTransferPasswordView;
    }

    @RequestMapping(value = "/showChangeMoblie", method = RequestMethod.GET)
    public String showSeurityChangeMoblieView(Model model) {
        return changeMoblieView;
    }

    /**
     * @param oldPassword 原始登录密码
     * @param newPassword 新登录密码
     * @param mobliecode  短信验证码
     * @Title: changeLoginPassword
     * @Description: TODO(修改当前用户的登录密码)
     * @author Jerry
     * @date 2016-10-21 12:32:45
     */
    @ResponseBody
    @RequestMapping(value = "/changeloginpassword", method = RequestMethod.POST)
    public Map<String, Object> changeLoginPassword(
            final @RequestParam String oldPassword,
            final @RequestParam String newPassword,
            final @RequestParam String mobliecode) {
        try {

            Map<String, Object> verifyResult = changePasswordVerify(mobliecode);
            if (verifyResult != null)
                return verifyResult;

            return super.changeLoginPassword(oldPassword, newPassword);

        } catch (Exception e) {
            logger.error(e, e);
            return WebResult.failure(e).toMap();
        }
    }

    /**
     * @param oldPassword 原始提现密码
     * @param newPassword 新提现密码
     * @param mobliecode  短信验证码
     * @Title: changeTransferPassword
     * @Description: TODO(修改当前用户的提现密码)
     * @author Jerry
     * @date 2016-10-21 12:32:45
     */
    @ResponseBody
    @RequestMapping(value = "/changereansferpassword", method = RequestMethod.POST)
    public Map<String, Object> changeTransferPassword(
            final @RequestParam String oldPassword,
            final @RequestParam String newPassword,
            final @RequestParam String mobliecode) {
        try {

            Map<String, Object> verifyResult = changePasswordVerify(mobliecode);
            if (verifyResult != null)
                return verifyResult;

            return super.changeTransferPassword(oldPassword, newPassword);

        } catch (Exception e) {
            logger.error(e, e);
            return WebResult.failure(e).toMap();
        }
    }

    /**
     * @param code   短信验证码
     * @param moblie 手机号码
     * @Title: changeUserMoblie
     * @Description: TODO(修改用户手机号码)
     * @author Jerry
     * @date 2016-10-20 07:59:24
     */
    @ResponseBody
    @RequestMapping(value = "/changeMoblie", method = RequestMethod.POST)
    public Map<String, Object> changeUserMoblie(
            final @RequestParam String code, final @RequestParam String moblie) {
        try {

            String SMScode = (String) SessionManager.getSessionAttribute(Constants.MOBILE_SMS_CODE);

            if (SMScode == null && "".equals(SMScode)) {
                return WebResult.failure("短信验证码以过期，请重新获取短信验证码。").put("failType", 1).infoKey("info").toMap();
            } else if (!SMScode.equals(code)) {
                return WebResult.failure("*验证码无效，请输入正确的验证码").put("failType", 1).infoKey("info").toMap();
            } else {
                Long currentUserID = privilegeService.getCurrentPrincipal()
                        .getUserid();
                SysUser user = new SysUser();
                user.setUserid(currentUserID);
                user.setMobile(moblie);
                user.setAdminid(currentUserID);
                user.setUpdatetime(new Date());

                sysUserService.updateByPrimaryKeySelective(user);

                return WebResult.success().info("修改手机成功").toMap();
            }
        } catch (Exception e) {
            logger.error(e, e);
            return WebResult.failure(e).toMap();
        }
    }

    /**
     * @return
     * @Title: showSeurityView
     * @Description: TODO(跳转账户与安全界面)
     * @author Jerry
     * @date 2016-10-20 07:13:36
     */
    @RequestMapping(value = "/showseurity", method = RequestMethod.GET)
    public String showSeurityView(Model model) {
        try {
            SysUser user = super.findSysUser(privilegeService
                    .getCurrentPrincipal().getUserid());
            UserInfo userinfo = new UserInfo();
            userinfo.setMobile(user.getMobile());
            userinfo.setUserid(user.getUserid());

            model.addAttribute("userinfo", userinfo);
        } catch (Exception e) {
            logger.error(e, e);
        }

        return securityView;
    }

    /**
     * @param userid      子账户ID
     * @param newpassword 子账户ID
     * @return
     * @Title: resetPassword
     * @Description: TODO(重置子账户密码)
     * @author Jerry
     * @date 2016-10-20 03:32:02
     */
    @ResponseBody
    @RequestMapping(value = "/resetChildUserPassword", method = RequestMethod.POST)
    public Map<String, Object> resetPassword(final @RequestParam Long userid,
                                             final @RequestParam String newpassword) {

        try {
            SysUser user = new SysUser();

            user.setUserid(userid);
            user.setAdminid(privilegeService.getCurrentPrincipal().getUserid());
            user.setUpdatetime(new Date());

            if (newpassword != null && "".equals(newpassword)) {
                user.setPassword(Constants.NOTIC_DEFAULT_USER_PASSWORD);
            } else {
                user.setPassword(newpassword);
            }

            super.changePassword(user);
            return WebResult.success().info("修改密码成功").toMap();
        } catch (Exception e) {
            logger.error(e, e);
            return WebResult.failure(e).toMap();
        }

    }

    /**
     * @param id 角色ID
     * @Title: showChildUserView
     * @Description: TODO(获取子账户信息)
     * @author Jerry
     * @date 2016-10-20 11:06:36
     */
    @RequestMapping(value = "/{roleid}/showchilduserinfo", method = RequestMethod.GET)
    public String showChildUserView(final @PathVariable("roleid") Long id, final String UserGroup,
                                    Model model) {

        String ug = "";

        try {
            ug = URLDecoder.decode(UserGroup, "UTF-8");
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            ug = "未知";
        } finally {
            QuerySysUserCondition condition = new QuerySysUserCondition();
            condition.setParentid(privilegeService.getCurrentPrincipal()
                    .getUserid());
            condition.setRoleid(id);

            List<SysUserDto> userDtos = sysUserService
                    .findChildUserByPrientIDAndRoleID(condition);

            ChildUser childUser = new ChildUser(new ArrayList<ChildUserInfo>(), ug);
            for (SysUserDto dto : userDtos) {
                ChildUserInfo info = new ChildUserInfo(dto.getTextCN(), dto.getUserid(), dto.getEmail(), dto.getUsername(), dto.getMobile(), dto.getPassword(), dto.getProperty(), dto.getRemark(), dto.getCreatetime(), dto.getOuttime());
                childUser.getInfos().add(info);
            }

            model.addAttribute("childUser", childUser);

            return childUserView;
        }

    }

    @RequestMapping(value = "/showusergroup", method = RequestMethod.GET)
    public String showUserGroupView(Model model) {

		/*
         * QuerySysRoleCondition condition = new QuerySysRoleCondition();
		 * condition.setQueryAll(true); PagingResult<SysRoleDto> pagingResult =
		 * super.getSysRoleDtoPagingResult(condition);
		 * 
		 * model.addAttribute("results",pagingResult);
		 */

        List<SysRole> sysRoles = sysRoleService
                .findChildRoleByBusinessUserID(privilegeService
                        .getCurrentPrincipal().getUserid());

        List<UserGroup> childUserGroups = new ArrayList<UserGroup>();
        for (SysRole sysrole : sysRoles) {
            UserGroup childUserGroup = new UserGroup();
            childUserGroup.setUserGroupid(sysrole.getRoleid());
            childUserGroup.setTextCN(sysrole.getNamecn());
            childUserGroups.add(childUserGroup);
        }
        model.addAttribute("childUserGroups", childUserGroups);
        return usergroupView;
    }

    /**
     * @Title: showBusinessInfoView
     * @Description: TODO(展示商业用户的信息)
     * @author Jerry
     * @date 2016-10-20 12:47:21
     */
    @RequestMapping(value = "/showbusinessinfo", method = RequestMethod.GET)
    public String showBusinessInfoView(Model model) {
        try {

            SysUser user = super.findSysUser(privilegeService
                    .getCurrentPrincipal().getUserid());

            UserInfo userInfo = new UserInfo(user.getUserid(),
                    user.getBusinessno(), user.getEmail(), user.getUsername(),
                    user.getMobile(), user.getUrl(), user.getRemark(),
                    user.getCreatetime(), user.getOuttime());
            String wechatAuthorization = user.getOpenid() == null ? ""
                    : "微信已授权";
            String moblieAuthorization = user.getMobileconfirmed() == 0 ? ""
                    : "手机已认证";
            String emailAuthorization = user.getEmailconfirmed() == 0 ? ""
                    : "邮箱已认证";

            userInfo.setConfirmedState(new String[]{wechatAuthorization,
                    moblieAuthorization, emailAuthorization});

            model.addAttribute("businessinfo", userInfo);

        } catch (Exception e) {
            logger.error(e, e);
        }
        return businessinfoView;
    }

    /**
     * @param SMScode 短信验证码
     * @return 返回 null 表示正常。不为空则是有异常，Controller直接响应客户端即可
     * @Title: changePasswordVerify
     * @Description: TODO(修改密码前验证)
     * @author Jerry
     * @date 2016-10-21 03:28:00
     */
    private Map<String, Object> changePasswordVerify(String SMScode)
            throws Exception {

        Map<String, Object> result = super.verifySeesionCode();

        if (super.verifyResult == false) {
            return result;
        }

        String sessionCode = result.get(Constants.MOBILE_SMS_CODE).toString();

        SysUser currentUser = super.findSysUser(privilegeService
                .getCurrentPrincipal().getUserid());

        result = super.verifyMoblieCode(currentUser.getMobile(), SMScode,
                sessionCode, currentUser.getMobile());

        if (result != null)
            return result;

        return null;
    }

    @ResponseBody
    @RequestMapping(value = "/submitCustomerInfo", method = RequestMethod.POST)
    public Map<String, Object> addCustomerInfo(final PubCustomer customer) {

        return null;
    }

    @ResponseBody
    @RequestMapping(value = "/changeCustomerInfo", method = RequestMethod.POST)
    public Map<String, Object> changeCustomerInfo(final PubCustomer customer) {

        return null;
    }
}
